package com.tzy.for10evalue.common.threadpool;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.core.task.TaskDecorator;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.Map;
import java.util.concurrent.ThreadPoolExecutor;

public class ThreadPoolUtil {
    private static Logger logger = LoggerFactory.getLogger(ThreadPoolUtil.class);

    private static ThreadPoolTaskExecutor sendPMTask;

    static {
        sendPMTask = new ThreadPoolTaskExecutor();
        sendPMTask.setTaskDecorator(new MdcTaskDecorator());
        sendPMTask.setCorePoolSize(4);//配置核心线程数
        sendPMTask.setMaxPoolSize(80);//配置最大线程数
        sendPMTask.setQueueCapacity(40000);//配置队列大小
        // 设置线程超时时间
        sendPMTask.setKeepAliveSeconds(80);
        // 设置线程名称前缀
        sendPMTask.setThreadNamePrefix("autoDeliverTask-");
        // 任务满直接丢弃
        sendPMTask.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy());
        sendPMTask.initialize();
    }

    public static void taskExecutor(Runnable t) {
        try {
            sendPMTask.submit(t);
        } catch (Exception e) {
            logger.error("autoDeliverTaskExecutor 异步执行异常",e);
        }
    }


    /**
     * 异步线程继续使用MDC上下文
     * */
   static class MdcTaskDecorator implements TaskDecorator {
        @Override
        public Runnable decorate(Runnable runnable) {
            // Right now: Web thread context !
            // (Grab the current thread MDC data)
            Map<String, String> contextMap = MDC.getCopyOfContextMap();
            return () -> {
                try {
                    // Right now: @Async thread context !
                    // (Restore the Web thread context's MDC data)
                    MDC.setContextMap(contextMap);
                    runnable.run();
                } finally {
                    MDC.clear();
                }
            };
        }
    }

}
